package service

import (
	"errors"
	"framework-server/global"
	"framework-server/model"
	"framework-server/model/request"
	"gorm.io/gorm"
	"strconv"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: getMenuTreeMap
//@description: 获取路由总树map
//@param: authorityId string
//@return: err error, treeMap map[string][]model.SysMenu

func getMenuTreeMap(authorityId string) (err error, treeMap map[string][]model.SysMenu) {
	var allMenus []model.SysMenu
	treeMap = make(map[string][]model.SysMenu)
	err = global.GVA_DB.Where("authority_id = ?", authorityId).Order("sort").Preload("Parameters").Find(&allMenus).Error
	for _, v := range allMenus {
		treeMap[v.ParentId] = append(treeMap[v.ParentId], v)
	}
	return err, treeMap
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetMenuTree
//@description: 获取动态菜单树
//@param: authorityId string
//@return: err error, menus []model.SysMenu

func GetMenuTree(authorityId string) (err error, menus []model.SysMenu) {
	err, menuTree := getMenuTreeMap(authorityId)
	menus = menuTree["0"]
	for i := 0; i < len(menus); i++ {
		err = getChildrenList(&menus[i], menuTree)
	}
	return err, menus
}



func GetMenuApis(info model.SysBaseMenu) (err error, apis []model.SysApi){
	err = global.GVA_DB.Where("menuId = ?", info.ID).Find(&apis).Error
	return
}


func SetMenuApis(info request.SetMenuApisRequest) (err error){
	var menu model.SysBaseMenu
	if errors.Is(global.GVA_DB.Where("id = ?", info.ID).First(&menu).Error, gorm.ErrRecordNotFound){
		return errors.New("菜单不存在")
	}
	menu.Apis = info.Apis
	err = global.GVA_DB.Save(&menu).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: getChildrenList
//@description: 获取子菜单
//@param: menu *model.SysMenu, treeMap map[string][]model.SysMenu
//@return: err error

func getChildrenList(menu *model.SysMenu, treeMap map[string][]model.SysMenu) (err error) {
	menu.Children = treeMap[menu.MenuId]
	for i := 0; i < len(menu.Children); i++ {
		err = getChildrenList(&menu.Children[i], treeMap)
	}
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetInfoList
//@description: 获取路由分页
//@return: err error, list interface{}, total int64

func GetInfoList() (err error, list interface{}, total int64) {
	var menuList []model.SysBaseMenu
	err, treeMap := getBaseMenuTreeMap()
	menuList = treeMap["0"]
	for i := 0; i < len(menuList); i++ {
		err = getBaseChildrenList(&menuList[i], treeMap)
	}
	return err, menuList, total
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: getBaseChildrenList
//@description: 获取菜单的子菜单
//@param: menu *model.SysBaseMenu, treeMap map[string][]model.SysBaseMenu
//@return: err error

func getBaseChildrenList(menu *model.SysBaseMenu, treeMap map[string][]model.SysBaseMenu) (err error) {
	menu.Children = treeMap[strconv.Itoa(int(menu.ID))]
	for i := 0; i < len(menu.Children); i++ {
		err = getBaseChildrenList(&menu.Children[i], treeMap)
	}
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: AddBaseMenu
//@description: 添加基础路由
//@param: menu model.SysBaseMenu
//@return: error

func AddBaseMenu(menu model.SysBaseMenu) error {
	if !errors.Is(global.GVA_DB.Where("name = ?", menu.Name).First(&model.SysBaseMenu{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在重复name，请修改name")
	}
	return global.GVA_DB.Create(&menu).Error
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: getBaseMenuTreeMap
//@description: 获取路由总树map
//@return: err error, treeMap map[string][]model.SysBaseMenu

func getBaseMenuTreeMap() (err error, treeMap map[string][]model.SysBaseMenu) {
	var allMenus []model.SysBaseMenu
	treeMap = make(map[string][]model.SysBaseMenu)
	err = global.GVA_DB.Order("sort").Preload("Parameters").Find(&allMenus).Error
	for _, v := range allMenus {
		treeMap[v.ParentId] = append(treeMap[v.ParentId], v)
	}
	return err, treeMap
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetBaseMenuTree
//@description: 获取基础路由树
//@return: err error, menus []model.SysBaseMenu

func GetBaseMenuTree(info request.GetBaseMenuTreeRequest) (err error, menus []model.SysBaseMenu) {
	if info.ParentId == "0"{  //如果是根角色，则获取全量菜单
		err, treeMap := getBaseMenuTreeMap()
		menus = treeMap["0"]
		for i := 0; i < len(menus); i++ {
			err = getBaseChildrenList(&menus[i], treeMap)
		}
		return err, menus
	}else{    //否则获取父角色的菜单
		err, ms := GetMenuAuthority(&request.GetAuthorityId{AuthorityId: info.ParentId}) //得到无层级的menus
		if err != nil{
			return err, nil
		}
		//将ms组装成有层级的菜单树
		treeMap := make(map[string][]model.SysBaseMenu)
		for _, v := range ms {
			treeMap[v.ParentId] = append(treeMap[v.ParentId], v.SysBaseMenu)

		}
		menus = treeMap["0"]
		for i := 0; i < len(menus); i++ {
			err = getBaseChildrenList(&menus[i], treeMap)
		}
		return err, menus
	}
	return nil, nil
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: AddMenuAuthority
//@description: 为角色增加menu树
//@param: menus []model.SysBaseMenu, authorityId string
//@return: err error
//更新角色对应的菜单
func AddMenuAuthority(menus []model.SysBaseMenu, authorityId string) (err error) {
	var auth model.SysAuthority
	auth.AuthorityId = authorityId
	auth.SysBaseMenus = menus
	err = SetMenuAuthority(&auth)
	if err != nil{
		return
	}
	//同时更新菜单关联的api
	//先获取菜单关联的api列表，再同步到casbin
	menuIds := []uint{}
	for _, v := range menus{
		menuIds = append(menuIds, v.ID)
	}
	var apis []model.SysApi
	err = global.GVA_DB.Where("menuId in ? or public = 1", menuIds).Find(&apis).Error
	if err != nil{
		return
	}
	//再获取原先绑定按钮的api列表
	err, buttonApis := GetButtonApiByAuthorityId(authorityId)
	apis = append(apis, buttonApis...)
	var casbinInfos = []request.CasbinInfo{}
	for _, api := range apis{
		casbinInfos = append(casbinInfos, request.CasbinInfo{
			Path: api.Path,
			Method: api.Method,
		})
	}
	err = UpdateCasbin(authorityId, casbinInfos)
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetMenuAuthority
//@description: 查看当前角色树
//@param: info *request.GetAuthorityId
//@return: err error, menus []model.SysMenu

func GetMenuAuthority(info *request.GetAuthorityId) (err error, menus []model.SysMenu) {
	err = global.GVA_DB.Where("authority_id = ? ", info.AuthorityId).Order("sort").Find(&menus).Error
	//sql := "SELECT authority_menu.keep_alive,authority_menu.default_menu,authority_menu.created_at,authority_menu.updated_at,authority_menu.deleted_at,authority_menu.menu_level,authority_menu.parent_id,authority_menu.path,authority_menu.`name`,authority_menu.hidden,authority_menu.component,authority_menu.title,authority_menu.icon,authority_menu.sort,authority_menu.menu_id,authority_menu.authority_id FROM authority_menu WHERE authority_menu.authority_id = ? ORDER BY authority_menu.sort ASC"
	//err = global.GVA_DB.Raw(sql, authorityId).Scan(&menus).Error
	return err, menus
}
